package com.nci.cloud.unit.management.FilePivotClientByProtoBuf;

import com.nci.cloud.unit.management.FilePivotClientByBytes.ClientThread;
import com.nci.cloud.unit.management.message.Message;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.stream.ChunkedWriteHandler;

public class FileClient {

    public void run(){
        final int PORT = 9999;
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer() {
                @Override
                protected void initChannel(Channel channel) throws Exception {
                    channel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                    channel.pipeline().addLast(new ProtobufEncoder());
                    channel.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                    channel.pipeline().addLast(new ProtobufDecoder(Message.TransRequest.getDefaultInstance()));
                    channel.pipeline().addLast(new ProtoBufClientHandler());
                }
            });
            ChannelFuture f = b.connect("localhost", PORT).sync();
            Channel channel = f.channel();
            if(channel.isActive()){
                System.out.println("start up client channel");
            }
            ClientThread ct = new ClientThread(channel);
            ct.start();
            ct.join();


        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            workerGroup.shutdownGracefully();
        }
    }// run

    public static void main(String[] args){
        new FileClient().run();
    }

}
